<template>
  <view class="chart-body">
    <!--#ifdef MP-ALIPAY -->
    <canvas
      id="performanceChart"
      canvas-id="performanceChart"
      type="2d"
      class="chart"
      :width="cWidth*pixelRatio"
      :height="cHeight*pixelRatio"
      :style="{'width':cWidth+'px','height':cHeight+'px'}" />
    <!--#endif-->
    <!--#ifndef MP-ALIPAY -->
    <canvas
      id="performanceChart"
      :style="{
        width: cWidth + 'px',
        height: cHeight + 'px'
      }"
      canvas-id="performanceChart"
      type="2d"
      class="chart" />
    <!--#endif-->

    <view class="info-box">
      <view class="box">
        <text class="mini-title">
          目标金额
        </text>
        <text class="info">
          {{ chartData.achievementMoneys || '0.00' }}元
        </text>
      </view>
      <view v-if="dropVal === 1" class="box">
        <text class="mini-title">
          业绩金额
        </text>
        <text class="info">
          {{ contractMoneys || '0.00' }}元
        </text>
      </view>
      <view v-if="dropVal === 2" class="box">
        <text class="mini-title">
          回款金额
        </text>
        <text class="info">
          {{ receivablesMoneys || '0.00' }}元
        </text>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    crmInstrumentQueryPerformance
  } from 'API/crm/work'
  import uCharts from '@/components/u-charts/u-charts.js'
  import { multiOperation, divideOperation } from '@/utils/lib.js'

  let performanceChart = null

  // 业绩指标完成率(仪表盘)
  export default {
    name: 'ChartPerformance',
    props: {
      params: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        cWidth: '',
        cHeight: '',
        pixelRatio: 1,
        serverData: '',

        loading: false,
        title: '',

        dropVal: null,
        chartData: {},
        contractMoneys: 0,
        receivablesMoneys: 0,
      }
    },
    watch: {
      params: {
        handler() {
          if (this.dropVal) {
            this.getData(this.dropVal)
          }
        },
        deep: true
      }
    },
    mounted() {
      const _self = this;
      // #ifdef MP-ALIPAY
      uni.getSystemInfo({
        success: function(res) {
          if (res.pixelRatio > 1) {
            // 正常这里给2就行，如果pixelRatio=3性能会降低一点
            // _self.pixelRatio =res.pixelRatio;
            _self.pixelRatio = 2;
          }
        }
      });
      // #endif
      this.cWidth = uni.upx2px(668);
      this.cHeight = uni.upx2px(450);
      this.gaugeWidth = uni.upx2px(30);
    },
    methods: {
      getData(status) {
        if (this.loading) return
        this.loading = true
        this.dropVal = status
        crmInstrumentQueryPerformance({
        ...this.params,
        type: status
        }).then(res => {
          this.loading = false
          if (res) {
            const num = Number(res.proportion) || 0
            const data = {
              series: [{
                name: '完成率',
                data: Number(divideOperation(num, 100).toFixed(4))
              }]
            }
            this.chartData = res
            this.initChart('performanceChart', data)
          }
          if (this.dropVal === 1 || this.dropVal === null) {
            this.contractMoneys = this.chartData.money
          } else {
            this.receivablesMoneys = this.chartData.money
          }
        }).catch(() => {
          this.loading = false
        })
      },

      initChart(canvasId, chartData) {
        const _self = this
        // #ifdef MP-WEIXIN
        this.$nextTick(function() {
          const query = uni.createSelectorQuery().in(this)
          query.select('#' + canvasId)
            .fields({ node: true, size: true })
            .exec(res => {
              // console.log('res: ', res[0])
              const data = res[0]
              const canvas = res[0].node
              const dpr = wx.getSystemInfoSync().pixelRatio
              const ctx = canvas.getContext('2d')
              const options = _self.getOptions(dpr, canvasId, chartData)
              options.context = ctx
              options.canvas2d = true
              if (dpr === 3) {
                options.extra.labelRadius = 10
                options.extra.labelCenterPosition = 4
              }
              canvas.width = options.width
              canvas.height = options.height
              // console.log('options: ', options)
              // eslint-disable-next-line new-cap
              performanceChart = new uCharts(options)
            })
        })
        // #endif
        // #ifndef MP-WEIXIN
        const options = _self.getOptions(_self.pixelRatio, canvasId, chartData)
        if (_self.pixelRatio === 3) {
          options.extra.labelRadius = 10
          options.extra.labelCenterPosition = 5
        }
        // eslint-disable-next-line new-cap
        performanceChart = new uCharts(options)
      // #endif
      },

      getOptions(dpr, canvasId, chartData) {
        const rate = multiOperation(chartData.series[0].data, 100)
        return {
          $this: this,
          canvasId: canvasId,
          type: 'gauge',
          fontSize: 11,
          padding: [0, 0, 0, 0],
          title: {
            name: rate + '%',
            color: '#666666',
            fontSize: 25 * dpr,
            offsetY: 50 * dpr, // 新增参数，自定义调整Y轴文案距离
          },
          subtitle: {
            name: '完成率',
            color: '#5F879D',
            fontSize: 14 * dpr,
            offsetY: -60 * dpr, // 新增参数，自定义调整Y轴文案距离
          },
          extra: {
            labelRadius: 0, // 自定义刻度label偏移
            labelCenterPosition: 0, // 自定义刻度label偏移
            gauge: {
              type: 'default',
              width: this.gaugeWidth * dpr, // 坐标轴（指示盘）线宽
              startAngle: 0.75,
              endAngle: 0.25,
              startNumber: 0,
              endNumber: 100,
              labelFormat: (d) => { return d },
              splitLine: {
                fixRadius: 0, // 刻度线径向偏移量
                splitNumber: 10, // 刻度线分段总数量
                width: this.gaugeWidth * dpr, // 仪表盘分割线长度
                color: '#FFFFFF',
                childNumber: 5, // 子刻度线数量
                childWidth: this.gaugeWidth * 0.4 * dpr // 仪表盘子刻度线长度
              },
              pointer: {
                width: this.gaugeWidth * 0.5 * dpr, // 指针宽度
                color: '#5F879D'
              }
            }
          },
          background: '#FFFFFF',
          pixelRatio: dpr,
          categories: [
            { value: 0.2, color: '#FF7474' },
            { value: 0.8, color: '#FECD51' },
            { value: 1, color: '#48E78D' },
          ],
          series: chartData.series.map(o => {
            return {
            ...o,
            data: Number(o.data > 1) ? 1 : o.data
            }
          }),
          animation: true,
          width: this.cWidth * dpr,
          height: this.cHeight * dpr,
          dataLabel: true
        }
      }
    }
  }
</script>

<style scoped lang="scss">
.chart-body {
  position: relative;
  padding: 20px 0 50rpx;

  .chart {
    width: 100%;
    height: 450rpx;
  }

  .info-box {
    position: absolute;
    left: 0;
    bottom: 30rpx;
    width: 100%;
    @include center;

    .box {
      width: 40%;
      flex-direction: column;
      @include center;

      .mini-title {
        color: #999;
        font-size: 24rpx;
      }

      .info {
        font-size: 28rpx;
        margin-top: 5rpx;
      }
    }
  }
}
</style>
